
import * as vscode from 'vscode';
import { html } from './configpage';
import { copyFileSync, createReadStream, createWriteStream } from 'fs';

var project: string
export function activate(context: vscode.ExtensionContext) {
	context.subscriptions.push(vscode.commands.registerCommand('gtinlian.config', () => {
		// 打开配置页面
		let panel = vscode.window.createWebviewPanel("", "", vscode.ViewColumn.One, {
			"enableScripts": true
		});
		panel.webview.html = html()
		panel.webview.onDidReceiveMessage((data) => {
			project = data
			vscode.window.showInformationMessage("配置项目成功: " + data)
			console.log(data)
		});
	}));

	// 拷贝文件
	function copyFile(sourcePath:string, destinationPath: string) {
		const sourceStream = createReadStream(sourcePath);
		const destinationStream = createWriteStream(destinationPath);
		sourceStream.pipe(destinationStream);
	}

	context.subscriptions.push(vscode.commands.registerCommand("gtinlian.save", () => {
		vscode.commands.executeCommand("workbench.action.files.save")

		let fileName = vscode.window.activeTextEditor?.document.fileName;
		console.log(fileName)
		console.log(project)
		// 如果是类文件则搜索类路径
		let sp = fileName?.split("src\\main\\java")
		// 如果是资源文件
		if (sp == null || sp?.length < 2) {
			sp = fileName?.split("src\\main\\resources")
			// webapp文件拷贝
			if (sp == null || sp?.length < 2) {
				if (fileName == null) {
					return;
				}
				// 如果不是webapp 文件则忽略
				if(fileName?.split("src\\main\\webapp").length < 2){
					return;
				}
				let projectClassFile = fileName?.split("src\\main")[0] + 'target\\' + project;
				try {
					copyFile(fileName, projectClassFile)
					vscode.window.showErrorMessage("更新资源文件需要重启tomcat"+fileName)
				} catch (e) {
					console.debug(e)
				}
				console.debug(fileName + " -> " + projectClassFile)
				return;
			}
			let classFile = sp[0] + 'target\\classes' + sp[1].replace(".java", "class");
			let projectClassFile = sp[0] + 'target\\' + project + '\\WEB-INF\\classes' + sp[1].replace(".java", "class");
			try {
				copyFile(classFile, projectClassFile)
				vscode.window.showErrorMessage("更新资源文件需要重启tomcat"+fileName)
			} catch (e) {
				console.debug(e)
			}
			console.debug(classFile + " -> " + projectClassFile)
			return;
		}
		let classFile = sp[0] + 'target\\classes' + sp[1].replace(".java", "class");
		let projectClassFile = sp[0] + 'target\\' + project + '\\WEB-INF\\classes' + sp[1].replace(".java", "class");
		try {
			copyFile(classFile, projectClassFile)
		} catch (e) {
			console.debug(e)
		}
		console.debug(classFile + " -> " + projectClassFile)
		vscode.window.showInformationMessage("更新成功:"+fileName)
	}));
}
export function deactivate() { }
